package com.woniuxy.meal.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.meal.common.RedisKey;
import com.woniuxy.meal.entity.UserAddress;
import com.woniuxy.meal.dao.UserAddressMapper;
import com.woniuxy.meal.exception.addressException.AddressException;
import com.woniuxy.meal.exception.addressException.AddressExceptionCode;
import com.woniuxy.meal.form.AddNewAddrForm;
import com.woniuxy.meal.form.ModifyAddrForm;
import com.woniuxy.meal.service.UserAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.meal.service.dto.GetAddressByUserIdDto;
import com.woniuxy.meal.util.RedisUtil;
import com.woniuxy.meal.util.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zz
 * @since 2023年06月12日
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements UserAddressService {

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 添加地址
     * @param form
     * @return
     * @throws Exception
     */
    @Override
    public UserAddress addNewAddr(AddNewAddrForm form) throws Exception {
        UserAddress userAddress = BeanUtil.toBean(form, UserAddress.class);
        String token = WebUtil.getRequest().getHeader("token");
        Long userId = redisUtil.getUserIdByToken(token);
        userAddress.setUserId(userId);
        userAddress.setDefaultArr(0);
        save(userAddress);
        return userAddress;
    }

    /**
     * 修改地址信息
     * @param form
     * @return
     * @throws Exception
     */
    @Override
    public void modifyAddr(ModifyAddrForm form) throws Exception {
        String token = WebUtil.getRequest().getHeader("token");
        Long userId = redisUtil.getUserIdByToken(token);
        UserAddress userAddress = getById(form.getId());
        if (userAddress==null||userId!=userAddress.getUserId().intValue()){
            throw new  AddressException(AddressExceptionCode.ADDRESS_NOT_EXIST);
        }
        if (form.getDefaultArr()!=null){
            if (form.getDefaultArr()==1){
                //将默认地址id存入redis中
                redisUtil.setString(RedisKey.getDefaultAddr(userId.intValue()),form.getId().toString());
            }
        }
        userAddress = BeanUtil.toBean(form, UserAddress.class);
        userAddress.setUserId(userId.longValue());
        updateById(userAddress);
    }

    /**
     * 获取某用户所有地址信息
     * @return
     * @throws Exception
     */
    @Override
    public List<GetAddressByUserIdDto> getUserAddress() throws Exception {
        String token = WebUtil.getRequest().getHeader("token");
        Long userId = redisUtil.getUserIdByToken(token);
        QueryWrapper<UserAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        List<UserAddress> list = userAddressMapper.selectList(queryWrapper);
        List<GetAddressByUserIdDto> dtoList = new ArrayList<>();

        //从redis中取出当前用户的默认地址id
        String defaultAddr = redisUtil.getString(RedisKey.getDefaultAddr(userId.intValue()));
        if (defaultAddr!=null&&!defaultAddr.equals("")){
            for (UserAddress userAddress : list) {
                GetAddressByUserIdDto dto = BeanUtil.toBean(userAddress, GetAddressByUserIdDto.class);
                dto.setDefaultArr(defaultAddr);
                dtoList.add(dto);
            }
        }else {
            for (UserAddress userAddress : list) {
                GetAddressByUserIdDto dto = BeanUtil.toBean(userAddress, GetAddressByUserIdDto.class);
                dto.setDefaultArr("0");
                dtoList.add(dto);
            }
        }
        System.out.println(dtoList);
        return dtoList;
    }

    /**
     * 删除地址
     * @param addressId
     */
    @Override
    public void delAddress(Long addressId) {
        String token = WebUtil.getRequest().getHeader("token");
        Long userId = redisUtil.getUserIdByToken(token);
        UserAddress userAddress = getById(addressId);
        if (userAddress==null||userAddress.getUserId().intValue()!=userId){
            throw new AddressException(AddressExceptionCode.ADDRESS_NOT_EXIST);
        }
        //判断删除的地址是不是默认地址
        String addrId = redisUtil.getString(RedisKey.getDefaultAddr(userId.intValue()));
        if (addressId.toString().equals(addrId)){
            redisUtil.delete(RedisKey.getDefaultAddr(userId.intValue()));
        }
        //从数据库中将当前地址信息删除
        removeById(userAddress);
    }
}
